#include "threadPool.h"

int exitPipe[2];
int userCheck(int netfd);
void handler(int signum)
{
    printf("sigum=%d\n", signum);
    write(exitPipe[1], "1", 1);
}

int main(int argc, char **argv)
{
    ARGS_CHECK(argc, 4);

    pipe(exitPipe);
    if (fork() != 0)
    {
        printf("pid=%d\n", getpid());
        close(exitPipe[0]);
        signal(SIGUSR1, handler);
        wait(NULL);
        exit(0);
    }

    close(exitPipe[1]);

    threadPool_t threadPool;
    int workernum = atoi(argv[3]);
    threadPoolInit(&threadPool, workernum);

    makeWorker(&threadPool);
    int sockfd;
    tcpInit(argv[1], argv[2], &sockfd);
    int epfd = epoll_create(1);
    epollAdd(epfd, sockfd);
    epollAdd(epfd, exitPipe[0]);

    struct epoll_event readyset[2];

    while (1)
    {
        int readynum = epoll_wait(epfd, readyset, 2, -1);
        for (int i = 0; i < readynum; ++i)
        {
            if (readyset[i].data.fd == sockfd)
            {
                int netfd = accept(sockfd, NULL, NULL);
                pthread_mutex_lock(&threadPool.taskQueue.mutex);
                taskEnQueue(&threadPool.taskQueue, netfd);
                printf("main thread send a task!\n");
                pthread_cond_signal(&threadPool.taskQueue.cond);
                pthread_mutex_unlock(&threadPool.taskQueue.mutex);
            }
            else if (readyset[i].data.fd == exitPipe[0])
            {
                printf("threadPool is going to exit!\n");
                pthread_mutex_lock(&threadPool.taskQueue.mutex);
                threadPool.exitFlag = 1;
                pthread_cond_broadcast(&threadPool.taskQueue.cond);
                pthread_mutex_unlock(&threadPool.taskQueue.mutex);
                for (int j = 0; j < workernum; ++j)
                {
                    pthread_join(threadPool.tidArr[j], NULL);
                }
                printf("main thread is closing!\n");
                exit(0);
            }
        }
    }
}
